#import "SpeedMath.h"
#import <Foundation/NSString.h>
#import <Foundation/Foundation.h>
#import "mathGameViewController.h"

@implementation SpeedMath

@synthesize mode;
@synthesize playerAnswerLabel;
@synthesize hiddenTextField;
@synthesize corr;
@synthesize eqn1Label, eqn2Label, eqn3Label;
@synthesize gameStatusLabel;
@synthesize startButton;
@synthesize buttons;
@synthesize playView;
@synthesize difficultyViewSpeedMath;
@synthesize tutorialView;
@synthesize timeLimitLabel;
@synthesize playerScoreLabel;
@synthesize modeLabel;
@synthesize menuView;
@synthesize endOfGameView;
@synthesize endEndlessPractice;
@synthesize currentView;
@synthesize numCorrectAnswersLabel; 
@synthesize numWrongAnswersLabel;
@synthesize gameModeLabel;
@synthesize finalScoreLabel;
@synthesize numCorrAnsLabel;
@synthesize numIncorrAnsLabel;
@synthesize timeUsedLabel;
@synthesize soundToggle;

-(void)setMode:(int)value{
	mode=value;
}

-(void)setMode1{
	mode = 1;
	[self initValues];
	modeText = @"1: Play for 60 seconds";
}
-(void)setMode2{
	mode = 2;
	[self initValues];
	modeText = @"2: Answer 100 Questions";
}
-(void)setMode3{
	mode = 3;
	[self initValues];
	modeText = @"3: Play until one incorrect";
}
-(void)setMode4{
	mode = 4;
	[self initValues];
	modeText = @"4: Endless Practice";
}
//turns sound on
- (void) soundOn{
	self.soundToggle=TRUE;
}

//turns sound off
- (void) soundOff{
	self.soundToggle=FALSE;
}
-(void)initValues{
	temporaryVariable = @"";
	numCorrectAnswers = 0;
	numWrongAnswers = 0;
	if(mode == 1){
		timeLimit = 60;
		timeLimitLabel.text = [NSString stringWithFormat:@"%d", timeLimit];
	}else{
		timeLimit = 0;
		timeLimitLabel.text = [NSString stringWithFormat:@"%d", timeLimit];
	}//
	
	playerScore = 0;
	playerScoreLabel.text = [NSString stringWithFormat:@"%d", playerScore];
	modeLabel.text = modeText;
	modeLabel.text = modeText;
}

-(IBAction)startGame:(id)sender{
	temporaryVariable = [NSString alloc];
	[self.view addSubview:playView];
	[self.view bringSubviewToFront:playView];
	playView.hidden = FALSE;
	while(numCorrectAnswers != 0 || numWrongAnswers != 0 || timeLimit != 60 || timeLimit != 0 || playerScore != 0)
	{
		[self initValues];
	}
	startButton.hidden = FALSE;
	currentView = self.view;
	
	//setup sound and music
	sound = [SoundController alloc];
	[sound initSoundController];
	[sound addSound:@"correct" filetype:@"wav"];
	[sound addSound:@"wrong" filetype:@"wav"];
}

-(IBAction)returnToMenu:(id)sender{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Return to Menu?" message:@"Are you sure you want to return to menu and end the game?" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];		
    [alert show];	
	[alert release];
}

-(void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	// the user clicked one of the OK/Cancel buttons
	if (buttonIndex == 0)
	{
		NSLog(@"ok");
		[self initValues];
		[self.view addSubview:menuView];
		[self.view bringSubviewToFront:menuView];
		[self dismissModalViewControllerAnimated:YES];
	}
	else
	{
		NSLog(@"cancel");
	}
}

-(IBAction)displayTypedNumber:(id)sender{
	/* Displays the string of currently typed number by the player. */
	
	currTyped = [sender titleForState:UIControlStateNormal];
	temporaryVariable = [temporaryVariable stringByAppendingString:currTyped];
	playerAnswerLabel.text = temporaryVariable;
}

-(IBAction)displayTypedOperand:(id)sender{
	/* Displays one operand currently typed by the player. */
	temporaryVariable = @"";
	NSString *currTyped = [sender titleForState:UIControlStateNormal];
	NSString *temporaryVariable2 = [[NSString alloc] initWithFormat: currTyped];
	playerAnswerLabel.text = temporaryVariable2;
}


-(IBAction)displayEqns:(id)sender{
	startButton.hidden = TRUE;
	buttons.hidden = TRUE;
	modeLabel.text = [NSString stringWithFormat:@"%d", mode];
	
	[self initValues];
	
	if(mode == 1){
		endTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(mode1Timer) userInfo:nil repeats:YES];
	}else{
		endTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(mode234Timer) userInfo:nil repeats:YES];
	}
	if(mode == 4){
		endEndlessPractice.hidden = FALSE;
	}
	numCorrectAnswers = 0; 
	numWrongAnswers = 0;  
	numCorrectAnswersLabel.text = [NSString stringWithFormat:@"%d", numCorrectAnswers];
	numWrongAnswersLabel.text = [NSString stringWithFormat:@"%d", numWrongAnswers];
	/* Display the three equations. */
	int randomNumberForQType = (arc4random()%(2));
	if(randomNumberForQType == 0)
		eqn1Label.text = [equationsModel createNumEqns];
	else
		eqn1Label.text = [equationsModel createOperEqns];
	answer1 = [equationsModel answerToEqns];
	
	randomNumberForQType = (arc4random()%(2));
	if(randomNumberForQType == 0)
		eqn2Label.text = [equationsModel createNumEqns];
	else
		eqn2Label.text = [equationsModel createOperEqns];
	answer2 = [equationsModel answerToEqns];
	
	randomNumberForQType = (arc4random()%(2));
	if(randomNumberForQType == 0)
		eqn3Label.text = [equationsModel createNumEqns];
	else
		eqn3Label.text = [equationsModel createOperEqns];
	answer3 = [equationsModel answerToEqns];
	
}

-(IBAction)punchEnter:(id)sender{
	/* Clear the previously entered answer. */
	playersAnswer = playerAnswerLabel.text;
	NSString *temporaryVariable3 = nil;
	playerAnswerLabel.text = temporaryVariable3;
	[self checkAnswer:sender];
	temporaryVariable = @"";
	[self changeEqns:sender];
}

-(IBAction)punchBack:(id)sender{
	/* Delete one character typed */
	NSString *backspace = playerAnswerLabel.text;
	int lengthofstring = backspace.length;
	if(lengthofstring >= 1)
		backspace = [backspace substringToIndex:lengthofstring - 1];
	playerAnswerLabel.text = backspace;
}

-(IBAction)punchEndGameCondition:(id)sender{
	[self endGameCondition];
}

-(void)endGameCondition{
	[self.view addSubview: endOfGameView];
	[self.view bringSubviewToFront: endOfGameView];
	endOfGameView.hidden = FALSE;
	
	[self showStatus];
}

-(IBAction)checkAnswer:(id)sender{
	numQuestions++;
	/* Check if the player's answer to the corresponding question is correct */
	if([playersAnswer isEqualToString:@"+"])
		playersAnswer = [NSString stringWithFormat:@"-1"];
	else if([playersAnswer isEqualToString:@"-"])
		playersAnswer = [NSString stringWithFormat:@"-2"];
	else if([playersAnswer isEqualToString:@"*"])
		playersAnswer = [NSString stringWithFormat:@"-3"];
	else if([playersAnswer isEqualToString:@"/"])
		playersAnswer = [NSString stringWithFormat:@"-4"];
	
	if ([playersAnswer isEqualToString: [NSString stringWithFormat:@"%d", answer1]]){
		corr.text = @"Correct";
		corr.backgroundColor = [UIColor greenColor];
		numCorrectAnswers++;
		numCorrectAnswersLabel.text = [NSString stringWithFormat:@"%d", numCorrectAnswers]; 
		playerScore = playerScore + 100;
		playerScoreLabel.text = [NSString stringWithFormat:@"%d", playerScore]; 
		if(soundToggle)
			[sound playSound:0];
	}else{
		corr.text = @"Incorrect";
		corr.backgroundColor = [UIColor redColor];
		numWrongAnswers++;
		numWrongAnswersLabel.text = [NSString stringWithFormat:@"%d", numWrongAnswers];
		playerScore = playerScore - 50;
		playerScoreLabel.text = [NSString stringWithFormat:@"%d", playerScore]; 
		if(soundToggle)
			[sound playSound:1];
	}
	
	//if need to end the game according to different game modes
	if(mode == 2){ //10 questions
		if(numQuestions == 100)
			[self endGameCondition];
	}else if(mode == 3){ //until one wrong
		if(numWrongAnswers == 1)
			[self endGameCondition];
	}
}

-(IBAction)changeEqns:(id)sender{ 
	/* Update to new set of equations */
	NSString *prevEqn2Label = eqn2Label.text;
	eqn1Label.text = prevEqn2Label;
	answer1 = answer2;
	
	NSString *prevEqn3Label = eqn3Label.text;
	eqn2Label.text = prevEqn3Label;
	answer2 = answer3;
	
	NSString *newEqn;
	int randomNumberForQType = (arc4random()%(2));
	if(randomNumberForQType == 0)
		newEqn = [equationsModel createNumEqns];
	else 
		newEqn = [equationsModel createOperEqns];
	eqn3Label.text = newEqn;
	answer3 = [equationsModel answerToEqns];	
}

-(int)keepPoints:(id)sender{
	return numCorrectAnswers;
}

-(void)mode1Timer{ //60 second race
	timeLimit -= 1;
	timeLimitLabel.text = [NSString stringWithFormat:@"%d", timeLimit];
	if(timeLimit <= 0){
		[self endGameCondition];
	}
}

-(void)mode234Timer{
	timeLimit += 1;
	timeLimitLabel.text = [NSString stringWithFormat:@"%d", timeLimit];
}

- (IBAction)backnnOne:(id)sender
{
	playView.hidden = TRUE;
	endOfGameView.hidden = FALSE; //show status page
	startButton.hidden = FALSE;
	[self initValues];
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)backnnnOne:(id)sender{
	endOfGameView.hidden = TRUE;
	startButton.hidden = FALSE;
	[self initValues];
}

-(void)showStatus{
	timeUsed = timeLimit;
	if(timeLimit < 0)
		timeUsed = 0;
	NSString *modeTypeText;
	if(mode == 1){
		modeTypeText = @"1: 60 Second Race";
		timeUsed = 60;
	}else if(mode == 2)
		modeTypeText = @"2: 100 Questions Challenge";
	else if(mode == 3)
		modeTypeText = @"3: Sudden Death";
	else 
		modeTypeText = @"4: Endless Practice";
	gameModeLabel.text = modeTypeText;
	finalScoreLabel.text = [NSString stringWithFormat:@"%d", playerScore];
	numCorrAnsLabel.text = [NSString stringWithFormat:@"%d", numCorrectAnswers];
	numIncorrAnsLabel.text = [NSString stringWithFormat:@"%d", numWrongAnswers];
	timeUsedLabel.text = [NSString stringWithFormat:@"%d", timeUsed];
}


-(IBAction)backToGameModeMenu:(id)sender{
	[self initValues];
	startButton.hidden = FALSE;
	[self.parentViewController showResetLabel];
	[self dismissModalViewControllerAnimated:YES];
}


/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */


// Implement loadView to create a view hierarchy programmatically, without using a nib.
/*- (void)loadView {
 }*/




// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	equationsModel = [Equations new];
	//[[[self navigationItem] backBarButtonItem] setTitle:@"Back"];
	[super viewDidLoad];
}




// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[playerAnswerLabel release];
	[equationsModel release];
	[hiddenTextField release];
	[corr release];
	[eqn1Label release];
	[eqn2Label release];
	[eqn3Label release];
	[super dealloc];
}

@end

